<?php

/**
 * Tworzy URL z podanego tekstu
 * 
 * @category   Core
 * @package    Core_Filter
 * @copyright  Copyright (c) 2008 Kuśmierz Adam
 * @author Adam Kuśmierz
 */

class Core_Filter_TitleURL implements Zend_Filter_Interface
{
	/**
	 * Validator to check if provided value exists (ie. in DB)
	 * @var Zend_Validate_Abstract
	 */
	protected $_validateExists = null;

	/**
	 * Constructor
	 *
	 * @param  Zend_Validate_Abstract $validateExists
	 * @return void
	 */
	public function __construct(Zend_Validate_Abstract $validateExists = null)
	{
		if ($validateExists) {
			$this->setValidator($validateExists);
		}
	}

	/**
	 * Set validator to check existing value
	 *
	 * @param Zend_Validate_Abstract $validator
	 * @return Core_Filter_Preamble
	 */
	public function setValidator(Zend_Validate_Abstract $validator)
	{
		if (!is_object($validator) || !($validator instanceof Zend_Validate_Abstract))
			throw new Zend_Filter_Exception('Validator should be Zend_Validate_Abstract type');
		
		$this->_validateExists = $validator;
		return $this;
	}

	/**
	 * Get prospective preamble length
	 *
	 * @return Zend_Validate_Abstract
	 */
	public function getValidator()
	{
		return $this->_validateExists;
	}
	
	/**
	 * Perform title generation filter
	 *
	 * @param string $text
	 * @return string
	 */
	public function filter($str)
	{
			$str = mb_strtolower($str, 'UTF-8');
			// usuwamy polskie znaki diakrytyczne
			$filter = new Core_Filter_ASCIIchars();
			$str = $filter->filter($str);
			//usuwamy usmieszki :d :p i takie tam
			$str = preg_replace(array('/((:|;)-?(p+|d+))+(\s|-|$)/i'), '-', $str);
			//zamianiamy spacje i inne na -
			$str = str_replace(array(' ', '-', '&', '.'), '-', $str);
			//zbedne znaki usuwamy
			$str = preg_replace('/[^a-z0-9_-]/i', '', $str);
			//usuwamy powtorzenia - i _
			$str = preg_replace('/(_*-+_*)/', '-', $str);
			$str = preg_replace('/-{2,}/', '-', $str);
			$str = preg_replace('/_{2,}/', '_', $str);
			$str = trim($str, '-_');
			
			//jesli po naszym zabiegu nic nie zostalo, warto jednak cos zwrocic...
			if (empty($str))
				$str = 'no-name';
			
			$validator = $this->getValidator();
			if (!is_null($validator)) {
				//spytaj bazy, czy juz jest taki, jesli taa, to walnij na koncu numerek
				$x = '';
				
				while(!$validator->isValid($str . $x))
					-- $x;
					
				$str .= $x;
			}
			
			return $str;
		}
	}